<template>
  <Top-Page class="details-label-box">
    <NavBar :title="title" leftArrow rightMore @click-left="navBack()" @click-right="show = !show" />

    <scroll-view
      scroll-y
      class="scroll-view"
      :scroll-into-view="'scroll-view-' + listCurID"
      :style="[{ height: 'calc(100vh - ' + (CustomBar + inlineTools + StatusBar) + 'px)' }]"
      :scroll-with-animation="true"
      :enable-back-to-top="true"
    >
      <view class="contacts-list">
        <view class="contacts-item-wrap border-bottom-after" v-for="(item, index) in contacts" :key="index">
          <view class="padding" :id="'scroll-view-' + item.name">{{ item.name }}</view>
          <view class="contacts-item" v-for="(it, ind) in item.children">
            <view class="contacts-item-right border-bottom-after">
              <image :src="it.avatar" class="contacts-it-avatar" />
              {{ it.realname }}
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <view class="indexBar" :style="[{ height: 'calc(100vh - ' + CustomBar + 'px - 50px)' }]">
      <view class="indexBar-box" @touchstart="tStart" @touchend="tEnd">
        <view
          class="indexBar-item"
          v-for="(item, index) in contacts"
          :key="index"
          :id="index"
          @touchstart="getCur"
          @touchend="setCur"
        >
          {{ item.name }}
        </view>
      </view>
    </view>

    <!--选择显示-->
    <view v-show="!hidden" class="indexToast">
      {{ listCur }}
    </view>

    <!-- 右上角的更多 -->
    <Popup v-model:show="show" position="bottom" closeable round class="more-popup">
      <view class="popup-more-item border-bottom-after" @click.stop="changeLabel('add')">添加好友</view>
      <view class="popup-more-item border-bottom-after" @click.stop="changeLabel('cut')">移除好友</view>
      <view class="popup-more-item border-bottom-after" @click.stop="(rename_show = !rename_show), (show = false)">
        更名此标签
      </view>
      <view class="popup-more-item" @click.stop="labelShowModal()">删除此标签</view>
    </Popup>

    <!-- 改名 -->
    <Popup v-model:show="rename_show" position="bottom" closeable round class="rename-popup">
      <input class="rename-popup-input" v-model="rename" focus placeholder="请输入新的标签名称" />
      <view class="rename-popup-btn" @click.stop="changeLabelRename()">完成</view>
    </Popup>
  </Top-Page>
</template>
<script>
import NavBar from '@/components/NavBar/NavBar.vue';
import Popup from '@/components/Popup/Popup.vue';
import { navBack } from '@/utils/utils.js';
import pinia from '@/store/index';
import { useFriendStore } from '@/store/friend.js';
const friendStore = useFriendStore(pinia);

export default {
  data() {
    return {
      navBack: navBack,
      show: false,
      rename_show: false,
      title: '标签',
      rename: '',
      query: {},
      listCurID: '',
      hidden: true,
      user_id_list: [],
      contacts: []
    };
  },
  components: { NavBar, Popup },
  onLoad(options) {
    Object.assign(this.query, options);
    this.title = options.title;
  },
  onShow() {
    this.contacts.length = 0;
    this.user_id_list.length = 0;
    this.firstApi();
  },
  methods: {
    firstApi() {
      const data = {
        label_id: this.query.id
      };
      this.$api.friendCircleApi.labelFriend(data).then((res) => {
        const contacts = res.data ?? [];

        if (Array.isArray(contacts) && contacts.length) {
          // 将联系人进行排序
          const sorted = contacts.sort((a, b) => {
            if (a.index === '#') {
              return 1;
            }
            if (b.index === '#') {
              return -1;
            }

            return a.index.localeCompare(b.index, 'zh');
          });

          // 重组联系人
          const result = sorted.reduce((acc, cur) => {
            //当前标签组的所有用户id
            this.user_id_list.push(cur.user_id);

            const index = cur.index;
            const existingIndex = acc.findIndex((item) => item.name === index);
            if (existingIndex === -1) {
              acc.push({ name: index, children: [cur] });
            } else {
              acc[existingIndex].children.push(cur);
            }

            return acc;
          }, []);

          this.contacts.length = 0;

          this.contacts.push(...result);
        }
      });
    },
    changeLabel(type) {
      this.show = false;
      let url = `type=${type}&id=${this.query.id}`;

      if (type == 'cut') {
        if (!this.contacts.length) {
          uni.showToast({
            title: '没有可移除的好友',
            icon: 'none'
          });
          return;
        }

        friendStore.changeLabelUsers(this.contacts);
      } else if (type === 'add') {
        url = `type=${type}&id=${this.query.id}&addList=${this.user_id_list.join()}`;
      }

      uni.navigateTo({
        url: `/pages/friend/options/options?${url}`
      });
    },
    //删除标签 -- 二次确认
    labelShowModal() {
      uni.showModal({
        title: '删除标签',
        content: '确认是否删除此标签？',
        showCancel: true,
        success: (res) => {
          if (res.confirm) {
            this.onLabelDel();
          } else if (res.cancel) {
            this.show = false;
          }
        }
      });
    },
    //删除标签
    onLabelDel() {
      const data = {
        label_id: this.query.id
      };

      this.$api.friendCircleApi.labelDel(data).then((res) => {
        if (res.code == 0) {
          this.navBack();
        }
      });
    },
    changeLabelRename() {
      if (!this.rename) {
        uni.showToast({
          title: '请输入新的标签名称',
          icon: 'none'
        });
        return;
      }

      const data = {
        label_id: this.query.id,
        title: this.rename
      };

      this.$api.friendCircleApi.labelRename(data).then((res) => {
        if (res.code == 0) {
          this.rename_show = false;
          this.title = this.rename;
        }
      });
    },
    onClickRight() {
      console.log('onClickRight');
    },
    setCur(e) {
      this.hidden = true;
      this.listCur = this.listCur;
    },
    //获取文字信息
    getCur(e) {
      this.hidden = false;

      this.listCur = this.contacts[e.target.id].name;
    },
    //触发全部开始选择
    tStart() {
      this.hidden = false;
    },
    //触发结束选择
    tEnd() {
      this.hidden = true;
      this.listCurID = this.listCur;
    }
  }
};
</script>

<style lang="scss">
@import './index.scss';
</style>
